import torch
from torch.autograd import Variable
import numpy as np

xy = np.loadtxt('./diabetes.csv',delimiter=',',dtype=np.float32)
# x_data:0 ~ cols ; y_data:cols - 1
x_data = Variable(torch.from_numpy(xy[:,0:-1]))
y_data = Variable(torch.from_numpy(xy[:,[-1]]))

print(xy.data.shape)
print(x_data.data.shape)
print(y_data.data.shape)

class Model(torch.nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.l1 = torch.nn.Linear(8, 6)
        self.l2 = torch.nn.Linear(6, 4)
        self.l3 = torch.nn.Linear(4, 1)
        self.sigmoid = torch.nn.Sigmoid()

    def forward(self,x):
        x = self.sigmoid(self.l1(x))
        x = self.sigmoid(self.l2(x))
        y_pred = self.sigmoid(self.l3(x))
        return y_pred

# our model
model = Model()

# print(model)
# exit(0)

cirterion = torch.nn.BCELoss(reduction='mean')
optimizer = torch.optim.SGD(model.parameters(),lr=0.01)

# train
for epoch in range(100000):
    y_pred = model(x_data)
    loss = cirterion(y_pred,y_data)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    if(epoch % 5000 == 0):
        print("loss ",epoch,loss.data)

# test model
# -0.294118,0.487437,0.180328,-0.292929,0,0.00149028,-0.53117,-0.0333333,0
h_our = Variable(torch.tensor([[-0.294118,0.487437,0.180328,-0.292929,0,0.00149028,-0.53117,-0.0333333]]))
print("predict : ",h_our.data[0],model.forward(h_our).data[0][0])
# -0.882353,-0.145729,0.0819672,-0.414141,0,-0.207153,-0.766866,-0.666667,1
h_our = Variable(torch.tensor([[-0.882353,-0.145729,0.0819672,-0.414141,0,-0.207153,-0.766866,-0.666667]]))
print("predict : ",h_our.data[0],model.forward(h_our).data[0][0])

# 保存网络
dummy_input = torch.randn(1, 1, 1, 8)
input_names = [ "actual_input_1" ]
output_names = [ "output1" ]
torch.onnx.export(model, dummy_input, "logistic.onnx", verbose=True, input_names=input_names, output_names=output_names)

# predict :  tensor([-0.2941,  0.4874,  0.1803, -0.2929,  0.0000,  0.0015, -0.5312, -0.0333]) tensor(0.3109)
# predict :  tensor([-0.8824, -0.1457,  0.0820, -0.4141,  0.0000, -0.2072, -0.7669, -0.6667]) tensor(0.9757) 
